import type {BigIntLiteral, Literal, RegExpLiteral, SimpleLiteral} from "estree";
import EstreeType from "./EstreeType.ts";

export default class EstreeLiteralCreate {
    static literal(value: string | boolean | number | RegExp | bigint | null | undefined): Literal {
        // 处理 null
        if (value === null) {
            return this.simpleLiteral(null);
        }
        // 处理 undefined
        if (value === undefined) {
            return this.simpleLiteral(undefined);
        }

        // 处理 RegExp
        if (value instanceof RegExp) {
            return this.regExpLiteral(value);
        }

        // 处理 BigInt
        if (typeof value === 'bigint') {
            return this.bigIntLiteral(value);
        }

        // 处理其他简单类型 (string | boolean | number)
        return this.simpleLiteral(value);
    }


    private static simpleLiteral(value: string | boolean | number | null | undefined): SimpleLiteral {
        return {
            type: EstreeType.literal,
            value,
            raw: typeof value === 'string'
                ? `"${value}"`  // 字符串加引号
                : String(value) // 其他类型直接转字符串
        };
    }

    private static regExpLiteral(value: RegExp): RegExpLiteral {
        return {
            type: EstreeType.literal,
            value: value,
            regex: {
                pattern: value.source,
                flags: value.flags
            },
            raw: value.toString()
        };
    }

    private static bigIntLiteral(value: bigint): BigIntLiteral {
        return {
            type: EstreeType.literal,
            value: value,
            bigint: value.toString(),
            raw: value.toString() + 'n'
        };
    }
}
